package org.jeecg.modules.youlgl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.repository.Model;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.ibatis.annotations.Param;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.youlgl.entity.HqYlgl;
import org.jeecg.modules.youlgl.mapper.HqYlglMapper;
import org.jeecg.modules.youlgl.service.IHqYlglService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.util.CollectionUtils;

import java.beans.Transient;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 油料管理
 * @Author: jeecg-boot
 * @Date:   2020-06-16
 * @Version: V1.0
 */
@Service
public class HqYlglServiceImpl extends ServiceImpl<HqYlglMapper, HqYlgl> implements IHqYlglService {


    @Autowired
    private IdentityService identityservice;
    @Autowired
    private RuntimeService runtimeservice;
    @Autowired
    private TaskService taskService;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private ISysUserService sysUserService;

    @Override
    public void startFlow(HqYlgl hqYlgl, LoginUser loginUser) {
        List<SysUser> shenpiren = sysUserService.queryByPost(loginUser.getOrgCode(),"shenpiren");
		if(CollectionUtils.isEmpty(shenpiren)) {
			throw new RuntimeException("当前部门审批人为空");
		}

        this.baseMapper.insert(hqYlgl);

        String businesskey = "" + hqYlgl.getId();

        identityservice.setAuthenticatedUserId(loginUser.getUsername());

        Map<String, Object> variables = new HashMap<String, Object>();
        variables.put("applyUser", loginUser.getUsername());
        variables.put("auditUser",shenpiren.get(0).getUsername());
        variables.put("carType", hqYlgl.getCarType());

        Model modelData = repositoryService.getModel("327501");
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(modelData.getDeploymentId()).singleResult();

        ProcessInstance instance=runtimeservice.startProcessInstanceById(processDefinition.getId(),businesskey,variables);
        String instanceid=instance.getId();
        hqYlgl.setProcessInstanceId(instanceid);
        Task task = taskService.createTaskQuery().processInstanceId(instance.getId()).taskAssignee(loginUser.getUsername()).singleResult();

        hqYlgl.setTaskId(task.getId());

        this.baseMapper.updateById(hqYlgl);

        taskService.complete(task.getId(),variables);
    }

    @Override
    public IPage<HqYlgl> taskList(String userId, Integer pageNo, Integer pageSize) {
        List<HqYlgl> gudingzichanList = new ArrayList<>();
        Model modelData = repositoryService.getModel("327501");
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(modelData.getDeploymentId()).singleResult();

        List<Task> taskList = taskService.createTaskQuery().processDefinitionId(processDefinition.getId()).taskAssignee(userId).listPage(pageNo-1,pageSize);
        Long total = taskService.createTaskQuery().processDefinitionId(processDefinition.getId()).taskAssignee(userId).count();
        taskList.forEach(task -> {
            String instanceId = task.getProcessInstanceId();
            HqYlgl hqYlgl = this.getOne(new LambdaQueryWrapper<HqYlgl>().eq(HqYlgl::getProcessInstanceId,instanceId));
            if(null != hqYlgl) {
                hqYlgl.setTaskId(task.getId());
                gudingzichanList.add(hqYlgl);
            }
        });
        IPage<HqYlgl> page = new Page<>(pageNo,pageSize);
        page.setRecords(gudingzichanList);
        page.setTotal(total);
        return page;
    }

    @Override
    public IPage<HqYlgl> myApplyList(Page<HqYlgl> page, LoginUser user, HqYlgl hqYlgl) {
        return this.baseMapper.myApplyList(page,user,hqYlgl);
    }

    @Override
    public IPage<HqYlgl> myTodoTasks(Page<HqYlgl> page, LoginUser user, HqYlgl hqYlgl) {
        return this.baseMapper.myTodoTasks(page,user,hqYlgl);
    }

    @Override
    public IPage<HqYlgl> myDoneTasks(Page<HqYlgl> page, LoginUser user, HqYlgl hqYlgl) {
        return this.baseMapper.myDoneTasks(page,user,hqYlgl);
    }

    @Override
    public List<HqYlgl> myApplyList2(LoginUser user, @Param("chepnu") String  chepnu) {
        return this.baseMapper.myApplyList2(user,chepnu);
    }

    @Override
    public void complateTask(LoginUser loginUser, String taskId, Integer status, String memo) {
//        taskService.claim(taskId,loginUser.getId());
        taskService.complete(taskId,new HashMap(){{
            put("status",status);
            put("memo",memo);
        }});
    }

    @Override
    @Transient
    public void applyAgain(HqYlgl hqYlgl, LoginUser user) {
        Task task = taskService.createTaskQuery().processInstanceId(hqYlgl.getProcessInstanceId()).taskAssignee(user.getUsername()).singleResult();
        hqYlgl.setTaskId(task.getId());

        this.baseMapper.updateById(hqYlgl);

        Map<String, Object> variables = new HashMap<String, Object>();
        variables.put("status",1);
        try {
            taskService.complete(task.getId(), variables);

        } catch (Exception errro) {
            throw new RuntimeException(errro.getMessage());
        }
    }
}
